/*
 * This file is part of Smart Route for S60 3rd Edition terminals
 * 
 * Copyright (C) 2006  Harri Salminen

 * This program free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 *(at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */
 

#include <barsread.h>
#include <stringloader.h>
#include <aknlists.h>
#include <eikenv.h>
#include <akniconarray.h>
#include <eikclbd.h>
#include <aknviewappui.h>
#include <eikappui.h>
#include "RouteListBox.h"
#include "SmartRoute.rsg"
#include "RouteListBoxView.h"
#include "SmartRoute.hrh"
#include "MainScreen.hrh"
#include "TripInfo.hrh"

CRouteListBox::CRouteListBox()
	{	
	}

CRouteListBox::~CRouteListBox()
	{
	delete iListBox;	
	iRouteIdArray.Close();
	}
				
CRouteListBox* CRouteListBox::NewL( 
		const TRect& aRect, 
		const CCoeControl* aParent, 
		MEikCommandObserver* aCommandObserver )
	{
	CRouteListBox* self = CRouteListBox::NewLC( aRect, aParent, aCommandObserver );
	CleanupStack::Pop( self );
	return self;
	}

CRouteListBox* CRouteListBox::NewLC( 
		const TRect& aRect, 
		const CCoeControl* aParent, 
		MEikCommandObserver* aCommandObserver )
	{
	CRouteListBox* self = new (ELeave) CRouteListBox();
	CleanupStack::PushL( self );
	self->ConstructL( aRect, aParent, aCommandObserver );
	return self;
	}
			
void CRouteListBox::ConstructL( 
		const TRect& aRect, 
		const CCoeControl* aParent, 
		MEikCommandObserver* aCommandObserver )
	{
    if (!aParent)
        {
    	CreateWindowL();
        }
    else
        {
        SetContainerWindowL( *aParent );
        }
	iFocusControl = NULL;
	iCommandObserver = aCommandObserver;
    InitializeControlsL();
    SetRect( aRect );
	ActivateL();
	}
			
TInt CRouteListBox::CountComponentControls() const
	{
	return (int) ELastControl;
	}
				
CCoeControl* CRouteListBox::ComponentControl( TInt aIndex ) const
	{
	switch ( aIndex )
		{
		case EListBox:
			return iListBox;
		}
	return NULL;
	}
							
void CRouteListBox::SizeChanged()
	{
	CCoeControl::SizeChanged();
	LayoutControls();
	}

void CRouteListBox::LayoutControls()
	{
	iListBox->SetExtent( TPoint( 0, 0 ), iListBox->MinimumSize() );
	}
			
TKeyResponse CRouteListBox::OfferKeyEventL( const TKeyEvent& aKeyEvent, TEventCode aType )
	{
	const TInt currItem = iListBox->CurrentItemIndex();
	
	if(iRouteIdArray.Count() > 0)
		iSelectedItemId = iRouteIdArray[currItem];
	else
		return EKeyWasConsumed;
	
	if ((aKeyEvent.iCode == EKeyLeftArrow ) || ( aKeyEvent.iCode == EKeyRightArrow))
	    {
	    return EKeyWasNotConsumed;
	    }
	
	if (aKeyEvent.iCode == EKeyOK) 
		{
		iCommandObserver->ProcessCommandL(ESmartRouteOpen);
		
		return EKeyWasConsumed;	
		}
		
	if (aKeyEvent.iCode == EKeyBackspace || aKeyEvent.iCode == EKeyDelete)
		{
		iCommandObserver->ProcessCommandL(ESmartRouteDelete);
		}
		
	if ( iFocusControl &&
			iFocusControl->OfferKeyEventL( aKeyEvent, aType ) == EKeyWasConsumed )
		return EKeyWasConsumed;
	return CCoeControl::OfferKeyEventL( aKeyEvent, aType );
	}
							
void CRouteListBox::InitializeControlsL()
	{
	iListBox = new (ELeave) CAknDoubleStyleListBox;
	iListBox->SetContainerWindowL( *this );
		{
		TResourceReader reader;
		iEikonEnv->CreateResourceReaderLC( reader, R_ROUTE_LIST_BOX_LIST_BOX );
		iListBox->ConstructFromResourceL( reader );
		CleanupStack::PopAndDestroy();
		}
	iListBox->Model()->SetOwnershipType( ELbmOwnsItemArray );
	SetupListBoxIconsL();
	iListBox->SetFocus( ETrue );
	iFocusControl = iListBox;
	
	}

void CRouteListBox::HandleResourceChange( TInt aType )
	{
	CCoeControl::HandleResourceChange( aType );
	SetRect( iAvkonViewAppUi->View( TUid::Uid( ERouteListBoxViewId ) )->ClientRect() );
	}
				
	
void CRouteListBox::Draw( const TRect& aRect ) const
	{
	CWindowGc& gc = SystemGc();
	gc.Clear( aRect );
	}
				
void CRouteListBox::AddListBoxItemL( CEikTextListBox* aListBox, const TDesC& aString )
	{
	CTextListBoxModel* model = aListBox->Model();
	CDesCArray* itemArray = static_cast< CDesCArray* > ( model->ItemTextArray() );
	itemArray->AppendL( aString );
	aListBox->HandleItemAdditionL();
	}

void CRouteListBox::ResetListL()
	{
	CTextListBoxModel* model = iListBox->Model();
	CDesCArray* itemArray = static_cast< CDesCArray* > ( model->ItemTextArray() );
	itemArray->Reset();
	iListBox->HandleItemRemovalL();
	}
					
RArray< TInt >* CRouteListBox::GetSelectedListBoxItemsLC( CEikTextListBox* aListBox )
	{
	CAknFilteredTextListBoxModel* model = 
		static_cast< CAknFilteredTextListBoxModel *> ( aListBox->Model() );
	if ( model->NumberOfItems() == 0 )
		return NULL;
		
	const CListBoxView::CSelectionIndexArray* selectionIndexes =
		aListBox->SelectionIndexes();
	TInt selectedIndexesCount = selectionIndexes->Count();
	if ( selectedIndexesCount == 0 )
		return NULL;

	RArray<TInt>* orderedSelectedIndices = 
		new (ELeave) RArray< TInt >( selectedIndexesCount );
	
	CleanupStack::PushL( orderedSelectedIndices );
	CleanupClosePushL( *orderedSelectedIndices );
	
	CAknListBoxFilterItems* filter = model->Filter();
	if ( filter != NULL )
		{
		for ( TInt idx = 0; idx < selectedIndexesCount; idx++ )
			{
			TInt filteredItem = ( *selectionIndexes ) [ idx ];
			TInt actualItem = filter->FilteredItemIndex ( filteredItem );
			orderedSelectedIndices->InsertInOrder( actualItem );
			}
		}
	else
		{
		for ( TInt idx = 0; idx < selectedIndexesCount; idx++ )
			orderedSelectedIndices->InsertInOrder( ( *selectionIndexes ) [ idx ] );
		}	
		
	return orderedSelectedIndices;
	}

void CRouteListBox::DeleteSelectedListBoxItemsL( CEikTextListBox* aListBox )
	{
	CAknFilteredTextListBoxModel* model = 
		static_cast< CAknFilteredTextListBoxModel *> ( aListBox->Model() );
	if ( model->NumberOfItems() == 0 )
		return;

	RArray< TInt >* orderedSelectedIndices = GetSelectedListBoxItemsLC( aListBox );		
	if ( !orderedSelectedIndices )
		return;

	CDesCArray* itemArray = static_cast< CDesCArray* > ( model->ItemTextArray() );
	TInt currentItem = 0;
	
	for ( TInt idx = orderedSelectedIndices->Count(); idx-- > 0; ) 
		{
		currentItem = ( *orderedSelectedIndices )[ idx ];
		itemArray->Delete ( currentItem );
		}

	CleanupStack::PopAndDestroy();
	CleanupStack::PopAndDestroy( orderedSelectedIndices );
	AknListBoxUtils::HandleItemRemovalAndPositionHighlightL(
		aListBox, currentItem, ETrue );
	}

CAknDoubleStyleListBox* CRouteListBox::ListBox()
	{
	return iListBox;
	}

void CRouteListBox::CreateListBoxItemL( TDes& aBuffer, const TDesC& aMainText,
		const TDesC& aSecondaryText )
	{
	_LIT ( KStringHeader, "\t%S\t%S" );

	aBuffer.Format( KStringHeader(), &aMainText, &aSecondaryText );
	}

void CRouteListBox::AddListBoxResourceArrayItemL( TInt aResourceId )
	{
	CDesCArray* array = iCoeEnv->ReadDesCArrayResourceL( aResourceId );
	CleanupStack::PushL( array );
	TBuf<512> listString; 
	CreateListBoxItemL( listString, ( *array ) [ 0 ], ( *array ) [ 1 ] );
	AddListBoxItemL( iListBox, listString );
	CleanupStack::PopAndDestroy( array );
	}

void CRouteListBox::SetupListBoxIconsL()
	{
	CArrayPtr< CGulIcon >* icons = NULL;		
	
	if ( icons )
		iListBox->ItemDrawer()->ColumnData()->SetIconArray( icons );
	}
	

TBool CRouteListBox::HandleMarkableListCommandL( TInt aCommand )
	{
	return EFalse;
	}
	

void CRouteListBox::AddItemsL(RArray<TShortRoute>& aPoints)
	{
	TShortRoute route;
	TBuf<128> listString; 
	TBuf<64>  routeTime;
	TBuf<KMaxTimeFormatSpec*2> tmpBuf;
	
	TInt startCount = iRouteIdArray.Count();
	iRouteIdArray.Reset();
	ResetListL();
	
	for(TInt i=0; i<aPoints.Count(); i++)
		{
		route = aPoints[i];
		
		route.iStart.FormatL(tmpBuf,TTimeFormatSpec());
		routeTime.Copy(tmpBuf);
		routeTime.Append(_L(" - "));
		route.iEnd.FormatL(tmpBuf,TTimeFormatSpec());
		routeTime.Append(tmpBuf);
		
		CreateListBoxItemL(listString,route.iShortName, routeTime);
		AddListBoxItemL(iListBox, listString);
		listString.Zero();  
		iRouteIdArray.Append(route.iId);
		}
	if(aPoints.Count())
		{
		iListBox->SetCurrentItemIndex(0);
		iSelectedItemId = iRouteIdArray[0];
		}
	if(startCount < iRouteIdArray.Count())
		iListBox->HandleItemAdditionL();
	else
		iListBox->HandleItemRemovalL();
	}

TUint32 CRouteListBox::SelectedItemId() const
	{
	return iSelectedItemId;
	}

TBool CRouteListBox::ListEmpty()
	{
	if(iRouteIdArray.Count() > 0)
		return EFalse;
	else
		return ETrue;
	}